package com.tidc.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tidc.manage.constant.ConstantField;
import com.tidc.manage.domain.ApplicationForm;
import com.tidc.manage.exception.ZeroException;
import com.tidc.manage.mapper.ApplicationFormMapper;
import com.tidc.manage.service.IApplicationFormService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 张朝锋
 * @author 张伟杰
 * @since 2018-09-23
 */
@Service
public class ApplicationFormServiceImpl extends ServiceImpl<ApplicationFormMapper, ApplicationForm> implements IApplicationFormService {

    @Override
    public Integer saveApplicationForm(ApplicationForm form) throws ZeroException {
        if (form.getIntroduce().trim().length() <= 0) {
            throw new ZeroException("Introduce.length");
        }
        form.setPostDate(System.currentTimeMillis() / 1000);
        form.setState(0);
        return baseMapper.insert(form);
    }

    @Override
    public ApplicationForm getSingleApplicationForm(String studentId) {
        return baseMapper.selectOne(new QueryWrapper<ApplicationForm>().eq("student_id", studentId));
    }

    @Override
    public List<ApplicationForm> listApplicationForms() {
        long now = System.currentTimeMillis() / 1000;
        //默认查看一个月内的申请表
        long defaultViewingTime = now-(ConstantField.ONE_MONTH);
        return baseMapper.selectList(
                new QueryWrapper<ApplicationForm>()
                        .between("post_date", defaultViewingTime, now)
                        .orderByDesc("post_date"));
    }

    @Override
    public Integer updateApplicationFormOfState(int id, ApplicationForm applicationForm) throws NotFoundException {
        ApplicationForm oldApplicationForm = baseMapper.selectById(id);
        if (oldApplicationForm == null) {
            throw new NotFoundException("ApplicationForm(" + id + ")");
        }
        baseMapper.updateApplicationFormForStateById(id, applicationForm.getState());
        return 1;
    }

    @Override
    public Integer deleteApplicationFormById(Long id) throws NotFoundException {
        if (baseMapper.selectById(id) == null) {
            throw new NotFoundException("ApplicationForm("+id+")");
        }
        return baseMapper.deleteById(id);
    }
}
